package com.zhima.controller.plain;

import cn.hutool.core.io.IoUtil;
import com.j256.simplemagic.ContentInfoUtil;
import com.zhima.dto.ZhimaOjResult;
import com.zhima.entity.OjFile;
import com.zhima.service.OjFileService;
import com.zhima.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.zhima.dto.ZhimaOjResult.success;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhima
 * @since 2023-08-25
 */
@RestController
@RequestMapping("/file")
public class OjFileController {
    @Autowired
    private OjFileService ojFileService;

    /**
     * 上传文件到bucket桶中
     *
     * @param file
     * @param bucket
     * @return
     * @throws IOException
     */
    @PostMapping("/{bucket}")
    public ZhimaOjResult uploadFile(@RequestBody MultipartFile file, @PathVariable("bucket") String bucket) throws IOException {
        return success(ojFileService.uploadFile(UserHolder.get().getId(), bucket, file.getOriginalFilename(), file.getBytes()));
    }
    
    /**
     * 根据文件id下载文件
     *
     * @param fileId
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable("fileId") Long fileId, HttpServletResponse response) throws IOException {
        OjFile ojFile = ojFileService.getById(fileId);
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s", URLEncoder.encode(ojFile.getFileName(), StandardCharsets.UTF_8.name())));
        response.setContentType(String.format("%s charset=utf-8", ContentInfoUtil.findExtensionMatch(ojFile.getFileName()).getMimeType()));
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setStatus(HttpServletResponse.SC_OK);
        IoUtil.copy(new ByteArrayInputStream(ojFileService.download(ojFile.getBucket(), ojFile.getUri())), response.getOutputStream());
    }

    /**
     * 下载指定文件id的文件
     *
     * @param fileId
     * @return
     */
    @GetMapping("/download/spj/{fileId}")
    public ZhimaOjResult downloadByFileId(@PathVariable("fileId") Long fileId) {
        return success(new String(ojFileService.downloadByFileId(fileId).getBytes(), StandardCharsets.UTF_8));
    }
}
